package cn.meye11.crm.service;

import cn.meye11.crm.common.DateUtils;
import cn.meye11.crm.common.RestResponse;
import cn.meye11.crm.common.StringUtils;
import cn.meye11.crm.domain.entity.MemberEntity;
import cn.meye11.crm.domain.entity.RechargeTimesEntity;
import cn.meye11.crm.domain.model.RechargeTimes;
import cn.meye11.crm.domain.query.RechargeTimesQuery;
import cn.meye11.crm.mapper.MemberMapper;
import cn.meye11.crm.mapper.RechargeTimesMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 充值记录表(RechargeTimes)表服务实现类
 * 默认CRUD操作
 * @author makejava
 * @since 2023-12-07 21:20:23
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class RechargeTimesService {

    private final RechargeTimesMapper rechargeTimesMapper;
    private final MemberMapper memberMapper;
    // 代码写到此区域
    
    
    /************************************* 请在上方编写新代码 **************************************/
    // 此区域为自动生成的通用代码 尽量不直接修改
    
    @Transactional(rollbackFor = Exception.class)
    public Long save(RechargeTimes model) {
        if (StringUtils.isNotBlank(model.getOperators())) {
            model.setCreatedBy(model.getOperators());
            model.setModifiedBy(model.getOperators());
        } else {
            model.setCreatedBy("Genkai");
            model.setModifiedBy("Genkai");
        }
        model.setRechargeTime(DateUtils.toLocalDateTime(new Date()));

        if (StringUtils.isBlank(model.getCreatedBy())) {
            throw new RuntimeException("创建人不能为空");
        }
        if (model.getId() != null) {
            throw new RuntimeException("主键id不可自定义");
        }
        if (model.getVersion() != null) {
            throw new RuntimeException("数据版本号不可自定义");
        }
        if (model.getTime() != null) {
            throw new RuntimeException("数据创建时间不可自定义");
        }
        if (model.getLast() != null) {
            throw new RuntimeException("数据修改时间不可自定义");
        }

        /* 重要： 充值完成后，需要更新会员表中的账户充值余额 和账户赠送余额信息*/
        MemberEntity member = memberMapper.selectByPrimaryKey(model.getMemberId());
        if (ObjectUtils.isEmpty(member)) {
            throw new RuntimeException("会员信息不存在，无法完成充值!");
        }
        if(Objects.isNull(model.getTimes()))
            model.setTimes(0);
        member.setTimes(Objects.isNull(member.getTimes()) ? model.getTimes() : member.getTimes() + model.getTimes());
        member.setId(model.getMemberId());
        memberMapper.updateByPrimaryKeySelective(member);
        
        RechargeTimesEntity entity = new RechargeTimesEntity(model);
        entity.setTime(DateUtils.toLocalDateTime(new Date()));
        entity.setLast(DateUtils.toLocalDateTime(new Date()));
        entity.setTimes(entity.getRemainingTimes());
        rechargeTimesMapper.insertSelective(entity);
        return entity.getId();
    }
    
    public void remove(RechargeTimes model) {
        
        if (model.getId() == null) {
            throw new RuntimeException("ID不能为空");
        }

        if (StringUtils.isBlank(model.getModifiedBy())) {
            throw new RuntimeException("修改人不能为空");
        }

        RechargeTimesEntity entity = rechargeTimesMapper.selectByPrimaryKey(model.getId());
        if (entity == null) {
            throw new RuntimeException("ID:" + model.getId() + "不存在");
        }
        rechargeTimesMapper.deleteByPrimaryKey(model.getId());
    }
    
    @Transactional(rollbackFor = Exception.class)
    public void update(RechargeTimes model) {
    
        if(model.getId() == null){
            throw new RuntimeException("ID不能为空");
        }
        
        if (StringUtils.isBlank(model.getModifiedBy())) {
            throw new RuntimeException("修改人不能为空");
        }
        
        RechargeTimesEntity entity = rechargeTimesMapper.selectByPrimaryKey(model.getId());
        if (entity == null) {
            throw new RuntimeException("ID:" + model.getId() + "不存在");
        }
        
        RechargeTimesEntity save = new RechargeTimesEntity(model);
        save.setLast(LocalDateTime.now());
        save.setTime(entity.getTime());
        rechargeTimesMapper.updateByPrimaryKey(save);
    }
    
    public RechargeTimes get(Long id) {
    RechargeTimesEntity entity = rechargeTimesMapper.selectByPrimaryKey(id);
    return entity == null ? null : new RechargeTimes(entity);
    }
    
    public Long count(RechargeTimesQuery query) {
        return rechargeTimesMapper.count(query);
    }
    
    public RestResponse<List<RechargeTimes>> list(RechargeTimesQuery query) {
        // 单次查不得大于32767条数据，否则需要分页
        query.setLimit((int) Short.MAX_VALUE);
        return page(query);
    }
    
    public RestResponse<List<RechargeTimes>> page(RechargeTimesQuery query) {
        PageHelper.startPage(query.getPage(), query.getLimit());
        List<RechargeTimesEntity> list = rechargeTimesMapper.list(query);
        PageInfo<RechargeTimesEntity> count = new PageInfo<>(list);
        List<RechargeTimes> collect = list.stream().map(RechargeTimes::new).collect(Collectors.toList());
        return RestResponse.success(count.getTotal(), collect);
    }
}
